import React, { useState, useEffect } from 'react'
import { Link, useNavigate, useLocation } from 'react-router-dom'
import { Mail, Phone, Eye, EyeOff, Loader2, CheckCircle, AlertCircle } from 'lucide-react'
import { useAuth } from '../contexts/AuthContext'
import '../styles/auth.css'

type LoginMethod = 'email' | 'phone'

const LoginPage: React.FC = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const { loginWithEmail, loginWithPhone, sendPhoneCode, isLoggedIn } = useAuth()

  const [loginMethod, setLoginMethod] = useState<LoginMethod>('email')
  const [loading, setLoading] = useState(false)
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null)

  // 邮箱登录状态
  const [emailData, setEmailData] = useState({
    email: '',
    password: '',
    showPassword: false
  })

  // 手机登录状态
  const [phoneData, setPhoneData] = useState({
    phone: '',
    code: '',
    codeSent: false,
    countdown: 0,
    devCode: '' // 开发环境显示的验证码
  })

  // 如果已登录，重定向到首页
  useEffect(() => {
    if (isLoggedIn) {
      const from = (location.state as any)?.from?.pathname || '/'
      navigate(from, { replace: true })
    }
  }, [isLoggedIn, navigate, location])

  // 验证码倒计时
  useEffect(() => {
    let timer: number
    if (phoneData.countdown > 0) {
      timer = setTimeout(() => {
        setPhoneData(prev => ({ ...prev, countdown: prev.countdown - 1 }))
      }, 1000) as unknown as number
    }
    return () => clearTimeout(timer)
  }, [phoneData.countdown])

  // 邮箱登录
  const handleEmailLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!emailData.email || !emailData.password) {
      setMessage({ type: 'error', text: '请填写邮箱和密码' })
      return
    }

    setLoading(true)
    setMessage(null)

    try {
      const result = await loginWithEmail(emailData.email, emailData.password)
      
      if (result.success) {
        setMessage({ type: 'success', text: result.message })
        // 登录成功后，useEffect会自动重定向
      } else {
        setMessage({ type: 'error', text: result.message })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '登录失败，请重试' })
    } finally {
      setLoading(false)
    }
  }

  // 发送验证码
  const handleSendCode = async () => {
    if (!phoneData.phone) {
      setMessage({ type: 'error', text: '请输入手机号' })
      return
    }

    if (!/^1[3-9]\d{9}$/.test(phoneData.phone)) {
      setMessage({ type: 'error', text: '手机号格式不正确' })
      return
    }

    setLoading(true)
    setMessage(null)

    try {
      const result = await sendPhoneCode(phoneData.phone, 'login')
      
      if (result.success) {
        setMessage({ type: 'success', text: result.message })
        setPhoneData(prev => ({
          ...prev,
          codeSent: true,
          countdown: 60,
          devCode: result.dev_code || '' // 开发环境显示验证码
        }))
      } else {
        setMessage({ type: 'error', text: result.message })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '发送验证码失败，请重试' })
    } finally {
      setLoading(false)
    }
  }

  // 手机登录
  const handlePhoneLogin = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!phoneData.phone || !phoneData.code) {
      setMessage({ type: 'error', text: '请输入手机号和验证码' })
      return
    }

    setLoading(true)
    setMessage(null)

    try {
      const result = await loginWithPhone(phoneData.phone, phoneData.code)
      
      if (result.success) {
        setMessage({ type: 'success', text: result.message })
        // 登录成功后，useEffect会自动重定向
      } else {
        setMessage({ type: 'error', text: result.message })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '登录失败，请重试' })
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center p-4 relative overflow-hidden">
      {/* 背景装饰 */}
      <div className="absolute inset-0">
        <div className="absolute top-10 left-10 w-32 h-32 bg-blue-200 rounded-full opacity-20 animate-pulse"></div>
        <div className="absolute top-40 right-20 w-24 h-24 bg-purple-200 rounded-full opacity-20 animate-pulse delay-1000"></div>
        <div className="absolute bottom-20 left-20 w-40 h-40 bg-indigo-200 rounded-full opacity-20 animate-pulse delay-2000"></div>
        <div className="absolute bottom-40 right-10 w-28 h-28 bg-pink-200 rounded-full opacity-20 animate-pulse delay-500"></div>
      </div>

      <div className="max-w-md w-full space-y-4 relative z-10">
        {/* 头部 */}
        <div className="text-center">
          <div className="mx-auto w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 rounded-2xl flex items-center justify-center mb-4 shadow-xl auth-float auth-pulse-glow">
            <span className="text-xl font-bold text-white">AI</span>
          </div>
          <h2 className="text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent">
            欢迎回来
          </h2>
          <p className="mt-3 text-theme-text-secondary">
            登录到您的 AIDE 智能助手
          </p>
          <p className="mt-2 text-sm text-theme-text-secondary">
            没有账号？{' '}
            <Link to="/register" className="text-blue-600 hover:text-blue-700 font-semibold transition-colors">
              立即注册 →
            </Link>
          </p>
        </div>

        {/* 主卡片 */}
        <div className="bg-theme-bg/80 backdrop-blur-xl rounded-3xl shadow-2xl border border-white/20 p-6 space-y-4 auth-card transition-all duration-300">
          {/* 登录方式切换 */}
          <div className="flex rounded-2xl bg-theme-bg-secondary/80 p-1.5 backdrop-blur-sm">
            <button
              onClick={() => setLoginMethod('email')}
              className={`flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-xl text-sm font-semibold transition-all duration-300 ${
                loginMethod === 'email'
                  ? 'bg-theme-bg text-blue-600 shadow-lg shadow-blue-100 transform scale-105'
                  : 'text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg/50'
              }`}
            >
              <Mail className="w-4 h-4" />
              邮箱登录
            </button>
            <button
              onClick={() => setLoginMethod('phone')}
              className={`flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-xl text-sm font-semibold transition-all duration-300 ${
                loginMethod === 'phone'
                  ? 'bg-theme-bg text-blue-600 shadow-lg shadow-blue-100 transform scale-105'
                  : 'text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg/50'
              }`}
            >
              <Phone className="w-4 h-4" />
              手机登录
            </button>
          </div>

          {/* 消息提示 */}
          {message && (
            <div className={`flex items-center gap-3 p-4 rounded-2xl text-sm font-medium ${
              message.type === 'success' 
                ? 'bg-green-50 text-green-800 border border-green-200/50 shadow-sm' 
                : 'bg-red-50 text-red-800 border border-red-200/50 shadow-sm'
            }`}>
              {message.type === 'success' ? (
                <CheckCircle className="w-5 h-5" />
              ) : (
                <AlertCircle className="w-5 h-5" />
              )}
              {message.text}
            </div>
          )}

          {/* 开发环境验证码显示 */}
          {phoneData.devCode && (
            <div className="bg-gradient-to-r from-yellow-50 to-amber-50 border border-yellow-200/50 rounded-2xl p-4 shadow-sm">
              <p className="text-sm text-yellow-800 font-medium">
                <strong>🔑 开发环境验证码：</strong> 
                <span className="font-mono text-lg ml-2 px-2 py-1 bg-yellow-100 rounded-lg">{phoneData.devCode}</span>
              </p>
            </div>
          )}

          {/* 邮箱登录表单 */}
          {loginMethod === 'email' && (
            <form onSubmit={handleEmailLogin} className="space-y-4">
              <div className="space-y-2">
                <label htmlFor="email" className="block text-sm font-semibold text-theme-text">
                  邮箱地址
                </label>
                <div className="relative">
                  <Mail className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5 pointer-events-none" />
                  <input
                    id="email"
                    type="email"
                    required
                    value={emailData.email}
                    onChange={(e) => setEmailData(prev => ({ ...prev, email: e.target.value }))}
                    className="w-full pl-12 pr-4 py-4 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg hover:bg-theme-bg-secondary"
                    placeholder="输入您的邮箱地址"
                  />
                </div>
              </div>

              <div className="space-y-2">
                <label htmlFor="password" className="block text-sm font-semibold text-theme-text">
                  密码
                </label>
                <div className="relative">
                  <input
                    id="password"
                    type={emailData.showPassword ? 'text' : 'password'}
                    required
                    value={emailData.password}
                    onChange={(e) => setEmailData(prev => ({ ...prev, password: e.target.value }))}
                    className="w-full pl-4 pr-12 py-4 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg"
                    placeholder="输入您的密码"
                  />
                  <button
                    type="button"
                    onClick={() => setEmailData(prev => ({ ...prev, showPassword: !prev.showPassword }))}
                    className="absolute inset-y-0 right-0 pr-4 flex items-center text-gray-400 hover:text-theme-text-secondary transition-colors"
                  >
                    {emailData.showPassword ? (
                      <EyeOff className="w-5 h-5" />
                    ) : (
                      <Eye className="w-5 h-5" />
                    )}
                  </button>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className="w-full flex justify-center items-center gap-2 py-4 px-6 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold rounded-2xl shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed transform hover:scale-[1.02] active:scale-[0.98]"
              >
                {loading ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <>
                    <Mail className="w-5 h-5" />
                    邮箱登录
                  </>
                )}
              </button>
            </form>
          )}

          {/* 手机登录表单 */}
          {loginMethod === 'phone' && (
            <form onSubmit={handlePhoneLogin} className="space-y-4">
              <div className="space-y-2">
                <label htmlFor="phone" className="block text-sm font-semibold text-theme-text">
                  手机号码
                </label>
                <div className="relative">
                  <Phone className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5 pointer-events-none" />
                  <input
                    id="phone"
                    type="tel"
                    required
                    value={phoneData.phone}
                    onChange={(e) => setPhoneData(prev => ({ ...prev, phone: e.target.value.replace(/\D/g, '') }))}
                    className="w-full pl-12 pr-4 py-4 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg hover:bg-theme-bg-secondary"
                    placeholder="输入您的手机号码"
                    maxLength={11}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <label htmlFor="code" className="block text-sm font-semibold text-theme-text">
                  验证码
                </label>
                <div className="flex gap-2">
                  <input
                    id="code"
                    type="text"
                    required
                    value={phoneData.code}
                    onChange={(e) => setPhoneData(prev => ({ ...prev, code: e.target.value.replace(/\D/g, '') }))}
                    className="flex-1 px-4 py-3 border border-theme-border rounded-2xl shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all duration-200 bg-theme-bg-secondary/50 focus:bg-theme-bg hover:bg-theme-bg-secondary"
                    placeholder="6位验证码"
                    maxLength={6}
                  />
                  <button
                    type="button"
                    onClick={handleSendCode}
                    disabled={loading || phoneData.countdown > 0}
                    className="px-4 py-3 border border-theme-border rounded-2xl text-xs font-semibold text-theme-text-secondary bg-theme-bg hover:bg-theme-bg-secondary focus:outline-none focus:ring-2 focus:ring-blue-500/20 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 hover:shadow-md whitespace-nowrap"
                  >
                    {phoneData.countdown > 0 ? `${phoneData.countdown}s` : '发送'}
                  </button>
                </div>
              </div>

              <button
                type="submit"
                disabled={loading || !phoneData.codeSent}
                className="w-full flex justify-center items-center gap-2 py-4 px-6 bg-gradient-to-r from-green-600 to-green-700 hover:from-green-700 hover:to-green-800 text-white font-semibold rounded-2xl shadow-lg hover:shadow-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed transform hover:scale-[1.02] active:scale-[0.98]"
              >
                {loading ? (
                  <Loader2 className="w-5 h-5 animate-spin" />
                ) : (
                  <>
                    <Phone className="w-5 h-5" />
                    手机登录
                  </>
                )}
              </button>
            </form>
          )}
        </div>

        {/* 底部提示 */}
        <div className="text-center space-y-2">
          <p className="text-xs text-theme-text-muted">
            登录即表示您同意我们的
            <button className="text-blue-600 hover:text-blue-700 mx-1 underline">服务条款</button>
            和
            <button className="text-blue-600 hover:text-blue-700 mx-1 underline">隐私政策</button>
          </p>
          <div className="flex items-center justify-center space-x-3 text-xs text-gray-400">
            <span>© 2024 AIDE</span>
            <span>•</span>
            <span>智能助手</span>
          </div>
        </div>
      </div>
    </div>
  )
}

export default LoginPage
